from rest_framework import serializers
from django.contrib.auth.models import Permission
from .models import Role, RolePermission


class PermissionSerializer(serializers.ModelSerializer):
    """
    序列化权限模型，用于显示权限的详细信息
    """
    class Meta:
        model = Permission
        fields = ['id', 'name', 'codename', 'content_type']


class RolePermissionSerializer(serializers.ModelSerializer):
    """
    序列化角色权限映射模型
    """
    permission = PermissionSerializer(read_only=True)

    class Meta:
        model = RolePermission
        fields = ['id', 'role', 'permission', 'created_at']


class RoleSerializer(serializers.ModelSerializer):
    """
    序列化角色模型
    """
    permissions = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = ['role_id', 'role_name', 'description', 'created_at', 'updated_at', 'permissions']

    def get_permissions(self, obj):
        """
        获取角色对应的权限列表
        """
        role_permissions = RolePermission.objects.filter(role=obj)
        return RolePermissionSerializer(role_permissions, many=True).data


class RoleCreateUpdateSerializer(serializers.ModelSerializer):
    """
    用于创建和更新角色的序列化器
    """
    permission_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False,
        help_text="分配给角色的权限ID列表"
    )

    class Meta:
        model = Role
        fields = ['role_name', 'description', 'permission_ids']

    def create(self, validated_data):
        """
        创建角色并分配权限
        """
        permission_ids = validated_data.pop('permission_ids', [])
        role = super().create(validated_data)

        for permission_id in permission_ids:
            try:
                permission = Permission.objects.get(id=permission_id)
                RolePermission.objects.create(role=role, permission=permission)
            except Permission.DoesNotExist:
                raise serializers.ValidationError(f"权限ID {permission_id} 不存在")

        return role

    def update(self, instance, validated_data):
        """
        更新角色信息并更新权限
        """
        permission_ids = validated_data.pop('permission_ids', None)
        role = super().update(instance, validated_data)

        if permission_ids is not None:
            # 删除当前角色所有权限
            RolePermission.objects.filter(role=role).delete()

            # 添加新权限
            for permission_id in permission_ids:
                try:
                    permission = Permission.objects.get(id=permission_id)
                    RolePermission.objects.create(role=role, permission=permission)
                except Permission.DoesNotExist:
                    raise serializers.ValidationError(f"权限ID {permission_id} 不存在")

        return role
